package com.lorenzogao.latte_core.net.callback

import android.os.Handler
import com.lorenzogao.latte_core.ui.LatteLoader
import com.lorenzogao.latte_core.ui.LoaderStyle
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 *  create by LorenzoGao
 *  email: 2508719070@qq.com
 *  TIME: 2020-01-08 15:18
 *  description:
 */

class RequestCallbacks : Callback<String> {


    val mRequest: IRequest?

    val mSuccess: ISuccess?

    val mFailure: IFailure?

    val mError: IError?

    private val LOADER_STYLE: LoaderStyle?

    companion object {
        val HANLDER = Handler()
    }


    constructor(
        request: IRequest?,
        success: ISuccess?,
        failure: IFailure?,
        error: IError?,
        loaderStyle: LoaderStyle?
    ) {
        this.mRequest = request
        this.mSuccess = success
        this.mFailure = failure
        this.mError = error
        this.LOADER_STYLE = loaderStyle
    }


    override fun onFailure(call: Call<String>, t: Throwable) {
        mFailure?.onFailure()
        stopLoading()
    }

    override fun onResponse(call: Call<String>, response: Response<String>) {
        if (response.isSuccessful) {
            if (call.isExecuted) {
                mSuccess?.onSuccess(response.body()!!)
            }
        } else {
            mError?.onError(response.code(), response.message())
        }
        mRequest?.onRequestEnd()


        stopLoading()

    }

    private fun stopLoading(){
        HANLDER.postDelayed({
            LOADER_STYLE?.let {
                LatteLoader.stopLoading()
            }
        }, 1000)
    }


}